# Importing Data
UK <- read_excel("C:/Users/Biniam/Desktop/Documents/Academic/Thesis/Analysis Folder/Excel Files/Egypt/UK.xlsx")

# Checking the Imported Data
View(UK)

# Creating Time Series Data
UK_ts <- ts(UK, start=c(2004,01), end=c(2019,07), frequency=12)

# Viewing and Checking the Created Time Series Data
UK_ts
sum(is.na(UK_ts))
library(forecast)
UK_ts <- tsclean(UK_ts)

# Step – 1 of the Box-Jenkins Methodology (Identification: Plotting the Time Series Data)
plot(UK_ts)
plot(aggregate(UK_ts,FUN=mean))

# Decomposing
UK_ts_decomp <- decompose(UK_ts)
plot(UK_ts_decomp)

# Testing for Stationarity
acf(UK_ts, lag.max=20)
pacf(UK_ts, lag.max=20)

# To see any seasonal effect
boxplot(UK_ts~cycle(UK_ts))

# To remove trend effect
UK_ts_diff <- diff(UK_ts)
plot(UK_ts_diff)

# To remove variance effect
UK_ts_log <- log(UK_ts)
plot(UK_ts_log)

# To remove both (Trend and Variance) effects
UK_ts_both <- diff(log(UK_ts))
plot(UK_ts_both)


# Dealing with ACF and PACF
install.packages("tseries")
library(tseries)
acf(UK_ts, lag.max=20)
acf(log(UK_ts), lag.max=20)
acf(diff(UK_ts), lag.max=20)
acf(diff(log(UK_ts)), lag.max=20)
pacf(UK_ts, lag.max=20)
pacf(log(UK_ts), lag.max=20)
pacf(diff(UK_ts), lag.max=20)
pacf(diff(log(UK_ts)), lag.max=20)

# Step-2 of the Box-Jenkins Methodology (Estimating the appropriate model)
UK_ts_model <- auto.arima(UK_ts)
UK_ts_model
UK_ts_model <- auto.arima(UK_ts, ic="aic", trace = TRUE)
UK_ts_model

# Step-3 of the Box-Jenkins Methodology (Diagnosis Checking)
library(tseries)
plot.ts(UK_ts_model$resid)
acf(UK_ts_model$residuals, main='ACF Residual')
pacf(UK_ts_model$residuals, main='ACF Residual')
Box.test(UK_ts_model$resid, lag=20, type="Ljung-Box")

# Forecasting
options(max.print=1000000)
library(forecast)
UK_ts_forecast <- forecast (UK_ts_model, level=c(95), h=257)
plot(UK_ts_forecast)
UK_ts_forecast             


write.table(UK_ts_forecast, file="UK_TSA.csv", sep=",")
